//
//  CelebrityBiographyDetailController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/7/22.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "CelebrityBiographyDetailController.h"
#import "DetailAuthorIntroduceCell.h"
#import "DetailAuthorParticularsIntroduceCell.h"
#import "DetailAuthorHeaderCell.h"
#import "DetailAuthorBottomCell.h"
#import "CommentDetailViewController.h"
#import "XLVideoPlayer.h"
#import "BigIntellgientModel.h"
#import "OpusListModel.h"
#import "UIImageView+WebCache.h"
#import "UITextField+LXDAdjust.h"
#import <AVFoundation/AVFoundation.h>
#import <UShareUI/UShareUI.h>
@interface CelebrityBiographyDetailController ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate,UITextFieldDelegate>



@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)UIWebView *webView;



@end

@implementation CelebrityBiographyDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
   
//    [self getDetailVcDataAccordingId:self.inforId];

}
-(void)viewWillAppear:(BOOL)animated{

    [self.dataArray removeAllObjects];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RefreshAndReload:) name:@"acceptInforIdAndRefresh" object:nil];
    [self getDetailVcDataAccordingId:self.inforId];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getTimelabelValue:) name:@"sendVideoTime" object:nil];
}
-(void)createTableViewUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - (64 + 40 + HEIGHT/3)) style:UITableViewStylePlain];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"DetailAuthorIntroduceCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"DetailAuthorIntroduceCell"];
    [self.tableView registerClass:[DetailAuthorParticularsIntroduceCell class] forCellReuseIdentifier:@"DetailAuthorParticularsIntroduceCell"];
    UINib *nib2 = [UINib nibWithNibName:@"DetailAuthorHeaderCell" bundle:nil];
    [self.tableView registerNib:nib2 forCellReuseIdentifier:@"DetailAuthorHeaderCell"];
    UINib *nib3 = [UINib nibWithNibName:@"DetailAuthorBottomCell" bundle:nil];
    [self.tableView registerNib:nib3 forCellReuseIdentifier:@"DetailAuthorBottomCell"];
    self.tableView.estimatedRowHeight = 200;
}
#pragma mark -tableView的代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BigIntellgientModel *model = self.dataArray[indexPath.row];
    if (indexPath.section == 0) {
        static NSString *cellId = @"DetailAuthorHeaderCell";
        DetailAuthorHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.titleLabel.text = model.fielName;
        cell.timeLabel.tag = 100001000;
        cell.timeLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"saveTime"];
        cell.watchCountLabel.text = model.watchCount;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.section == 1){
        static NSString *cellId = @"DetailAuthorIntroduceCell";
        DetailAuthorIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.authorNameLabel.text = model.authorName;
        cell.authorDescrLabel.text  = model.auhtorDescrp;
        cell.authorIntroLabel.text = model.auhtorIntroe;
        [cell.authorPicImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PictureIp,model.authorImagepath]] placeholderImage:[UIImage imageNamed:@""]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.section == 2){
        static NSString *cellId = @"DetailAuthorParticularsIntroduceCell";
        DetailAuthorParticularsIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        [cell.contentView addSubview:_webView];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else{
        static NSString *cellId = @"DetailAuthorBottomCell";
        DetailAuthorBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        [cell.commentBtn addTarget:self action:@selector(gotoCommentPage) forControlEvents:UIControlEventTouchUpInside];
        [cell.loveBtn addTarget:self action:@selector(gotoSharePage) forControlEvents:UIControlEventTouchUpInside];
        [cell.talkTextfield setAutoAdjust:YES];
        cell.talkTextfield.delegate = self;
//        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return scaleTopAndBottom(70);
    }else if (indexPath.section == 1){
        return UITableViewAutomaticDimension;
    }else if (indexPath.section == 2){
         return _webView.frame.size.height;;
    }else{
        return scaleTopAndBottom(175);
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 3) {
        return 0;
    }else{
        return scaleTopAndBottom(50);
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        return nil;
    }else if (section == 1){
        return [self createHeaderViewAboutUI:@"作者介绍" AndAddSubviewToFatherview:view];
    }else if (section == 2){
        return [self createHeaderViewAboutUI:@"详情介绍" AndAddSubviewToFatherview:view];
    }else{
        return nil;
    }
}
//创建tableview的头部视图
-(UIView *)createHeaderViewAboutUI:(NSString *)headerTitle AndAddSubviewToFatherview:(UIView *)fatherView{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor yellowColor];
    [fatherView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fatherView.mas_centerY);
        make.left.equalTo(fatherView.mas_left);
        make.height.mas_equalTo(25);
        make.width.mas_equalTo(scaleLeftAndRight(2));
    }];
    UILabel *lable = [[UILabel alloc] init];
    [fatherView addSubview:lable];
    lable.text = headerTitle;
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_right).offset(scaleLeftAndRight(10));
        make.top.equalTo(fatherView.mas_top);
        make.bottom.equalTo(fatherView.mas_bottom);
        make.right.equalTo(fatherView.mas_right).offset(scaleLeftAndRight(-10));
    }];
    return fatherView;
}


#pragma mark - UIScrollViewDelegate和取消区头的停滞效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.tableView]){
    }
    CGFloat sectionHeaderHeight = scaleTopAndBottom(50);
    if (scrollView.contentOffset.y <=sectionHeaderHeight && scrollView.contentOffset.y >=  0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y >=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


/**
 跳转到评论页面
 */
-(void)gotoCommentPage{
    CommentDetailViewController *commentVc = [[CommentDetailViewController alloc] init];
    if (self.goBlock) {
        self.goBlock(commentVc);
    }
}

/**
 跳转到分享界面
 */
-(void)gotoSharePage{
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_WechatSession)]];
    __weak typeof(self) weakself = self;
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        __strong typeof(self) strongself = weakself;
        [strongself shareWebPageToPlatformType:platformType];
    }];
}
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"欢迎使用【途吉儿童派】" descr:@"欢迎使用【途吉儿童派】，李大师倾力推荐，助力您的产品开发、运营与推广！" thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = @"http://www.baidu.com";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

#pragma mark -获取数据
-(void)getDetailVcDataAccordingId:(NSString *)inforId {
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSDictionary *param = @{@"id":inforId,@"type":self.type};
        NSString *url = ServerIp@"/opusApp/detail";
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            BigIntellgientModel *model = [BigIntellgientModel modelWithDictionary:jsonDict];
            [self.dataArray addObject:model];
            NSLog(@"这是名字%@",model.fielName);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self createTableViewUI];
                _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
                _webView.delegate = self;
                _webView.scrollView.scrollEnabled = NO;
                [_webView loadHTMLString:model.content baseURL:nil];
                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];

    });

}
#pragma mark - UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取到webview的高度
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x ,self.webView.frame.origin.y, WIDTH, height);
    
    [self.tableView reloadData];
    
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //预览图片
    if ([request.URL.scheme isEqualToString:@"image-preview"]) {
        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"我是被点击的图片");
        return NO;
    }
    return YES;

}
#pragma mark -textfil的代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark -数组延迟加载
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma makr -通知的方法执行
-(void)RefreshAndReload:(NSNotification *)infro{
    self.inforId = infro.userInfo[@"opusID"];
}
-(void)getTimelabelValue:(NSNotification *)infor{
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    DetailAuthorHeaderCell *cell = [self.tableView cellForRowAtIndexPath:index];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"saveTime"]) {
        cell.timeLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"saveTime"];
    }else{
      cell.timeLabel.text = infor.userInfo[@"totalTime"];
    }
    
}

@end
